﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Collections;
using System.Web;

/**********************
 要在 app.config 加入
   <system.net>
    <settings>
      <httpWebRequest useUnsafeHeaderParsing = "true"/>
    </settings>
  </system.net>
 ********************/

namespace NetLib.web
{
    public class HttpPost
    {
        public static string Request(string url, Hashtable parameter, Encoding enc, Hashtable headers = null)
        {
            if (headers == null)
                headers = new Hashtable();
            String result = "";
            using (WebClient wc = new WebClient())
            {
                wc.Encoding = enc;
                if (null != headers)
                    foreach (String k in headers.Keys)
                    {
                        wc.Headers.Add(k, (String)headers[k]);
                    }
                StringBuilder sb = new StringBuilder();
                foreach (String k in parameter.Keys)
                {
                    sb.Append(k);
                    sb.Append("=");
                    String v = (String)parameter[k];
                    v = HttpUtility.UrlEncode(v);
                    sb.Append(v);
                    sb.Append("&");
                }
                String ps = sb.ToString();
                var URI = new Uri(url);
                if (headers.Contains("Content-Type") == false)
                    wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
                try
                {
                    
                    byte[] postdata = Encoding.UTF8.GetBytes(ps);
                    byte[] responsedata = wc.UploadData(url, postdata);
                    
                    String contentBig5 = System.Text.Encoding.GetEncoding("big5").GetString(responsedata);
                    String contentUtf8 = System.Text.Encoding.UTF8.GetString(responsedata);

                    if (Encoding.UTF8.Equals(enc))
                        result= contentUtf8;
                    else
                        result = contentBig5;

                }
                catch (Exception e)
                {
                    result = "Error:" + e.Message;
                }
            }
            return result;
        }
    }

}
